<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card" >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="UserInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <!-- 状态 -->
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!--修改用户  -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleClick(scope.row.id)"
              size="mini"
            ></el-button>
            <!-- 删除用户 -->
            <el-button
              type="danger"
              icon="el-icon-share"
              size="mini"
              @click="removeUserAction(scope.row.id)"
            ></el-button>
            <!--  -->
            <el-tooltip
              content="分配角色"
              placement="top"
              effect="light"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="UserInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="UserInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加对话框 -->
    <UserForm v-model="dialogVisible" :getUserList="getUserList"></UserForm>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisivle"
      width="30%"
    >
      <el-form
        :model="editForm"
        label-position="left"
        label-width="100px"
        ref="changeUser"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            autocomplete="off"
            v-model="editForm.username"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input autocomplete="off" v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input autocomplete="off" v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisivle = false">取 消</el-button>
        <el-button type="primary" @click="changeUserAction">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="showRole"
      width="30%"
      @close="roleCloseAction"
    >
      <div>
        <p>当前的用户:{{ roleInfo.username }}</p>
        <p>当前的用户:{{ roleInfo.role_name }}</p>
        <p>
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleAll"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRole = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import UserForm from './children/UserForm.vue'
import axios from '@/axios/axios'
import rules from '@/mixin/rules.js'
import http from '@/axios/user.js'
export default {
  name: 'Users',
  components: {
    [UserForm.name]: UserForm,
  },
  mixins: [rules],
  data() {
    return {
      UserInfo: {
        query: '',
        // 第几页
        pagenum: 1,
        //每页的条目数
        pagesize: 2,
      },
      userList: [],
      //总条目数
      total: 0,
      dialogVisible: false, //控制对话框显示隐藏
      editDialogVisivle: false, //修改用户对话框的显示隐藏
      //用户的信息
      editForm: {},
      showRole: false, //分配角色对话框
      roleInfo: {}, //分配角色的信息
      roleAll: [], //所有角色信息
      selectedRoleId: '', //选中的角色
    }
  },
  methods: {
    //用户列表数据请求
    async getUserList() {
      const { data } = await axios.get('/users', this.UserInfo)
      //console.log(data)
      if (data.meta.status != 200) {
        return this.$message.error(data.meta.msg)
      }
      this.userList = data.data.users
      this.total = data.data.total
    },
    //用户状态
    async userStateChange(row) {
      //console.log(row);
      const { data } = await axios.put(`users/${row.id}/state/${row.mg_state}`)
      console.log(data)
      if (data.meta.status !== 200) {
        row.mg_state = !row.mg_state
        this.$message.error(data.meta.msg)
        return
      }
      this.$message.success(data.meta.msg)
    },
    //修改用户
    async handleClick(id) {
      const { data } = await axios.get(`users/${id}`)
      if (data.meta.status != 200) {
        return this.$message.error(data.meta.msg)
      }
      this.$message.success(data.meta.msg)
      //console.log(data)
      this.editForm = data.data
      this.editDialogVisivle = true
    },
    // 分页
    handleSizeChange(val) {
      this.UserInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.UserInfo.pagenum = val
      this.getUserList()
    },
    //用户信息修改请求
    changeUserAction() {
      this.$refs.changeUser.validate(async (res) => {
        if (!res) return
        const { data } = await http.put(`/users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        })
        if (data.meta.status !== 200) {
          return this.$message.error(data.meta.msg)
        }
        this.$message.success(data.meta.msg)
        this.editDialogVisivle = false
        this.getUserList()
      })
    },
    //删除单个用户
    async removeUserAction(id) {
      const res = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //console.log(res)
      if (res !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data } = await http.delete(`/users/${id}`)
      console.log(data)
      if (data.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success(data.meta.msg)
      this.getUserList()
    },
    //角色分配
    async setRole(row) {
      //console.log(row)
      this.roleInfo = row
      const { data } = await http.get('/roles')
      console.log(data)
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg)
      }
      this.roleAll = data.data
      this.showRole = true
    },
    //保存选中角色请求
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择角色')
      }
      const { data } = await http.put(`/users/${this.roleInfo.id}/role`, {
        rid: this.selectedRoleId,
      })
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg)
      }
      this.$message.success(data.meta.msg)
      //console.log(data);
      this.getUserList()
      this.showRole = false
    },
    roleCloseAction() {
      //console.log(1)
      this.selectedRoleId = ''
    },
  },
  created() {
    this.getUserList()
  },
}
</script>

<style>
</style>